package org.paraj.mapreduce.executors.grid;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

import org.paraj.misc.EnvironmentException;

public class Serializer{
    public Object deserialize(byte[] binary){
        try{
            return new ObjectInputStream(new ByteArrayInputStream(binary)).readObject();
        } catch(Throwable e){
            throw new EnvironmentException("Error while desirializing task runnable", e);
        }
    }

    public byte[] serialize(Object runnable){
        try{
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(runnable);
            objectOutputStream.close();
            byteArrayOutputStream.close();

            return byteArrayOutputStream.toByteArray();
        } catch(IOException e){
            throw new EnvironmentException("Error while serializing "+runnable, e);
        }
    }
}
